package com.wlz.demo.common.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWTException;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.wlz.demo.common.ResultUtil;
import com.wlz.demo.entity.User;
import com.wlz.demo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private IUserService iUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        //如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)){
            return true;
        }

        //执行认证
        if (StrUtil.isBlank(token)){
            ResultUtil.fail(401,"无token 请重新登录");
            return false;
        }

        //获取token中的user-id
        String useId = "";
        try {
            useId = JWT.decode(token).getAudience().get(0);
        }catch (JWTException j){
            ResultUtil.fail(401,"token 验证失败 请重新登录");
        }

        //根据token-user-id查数据库

        User user = iUserService.getById(useId);
        if (user == null){
            ResultUtil.fail(401,"用户不存在 请重新登录");
            return false;
        }

        //用户密码加签验证 token

        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try{
            //验证token
           jwtVerifier.verify(token);
        }catch (JWTVerificationException e){
            ResultUtil.fail(401,"token 验证失败 请重新登录");
        }

        return true;
    }
}
